﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Weazel.Willows.PreliminaryModel
{
	public class ChildModule
	{
		/// <summary>
		/// Name of the module containing the implementation
		/// of this child module
		/// </summary>
		private string moduleImplementationName;
		public string ModuleImplementationName
		{
			get { return moduleImplementationName; }			
		}

		/// <summary>
		/// Localname or alias of the child module
		/// </summary>
		private string moduleAlias;
		public string ModuleAlias
		{
			get { return moduleAlias; }			
		}

		/// <summary>
		/// Map mapping names of connectors on the child module
		/// to connections (queues, signals .. ) on the parent module
		/// </summary>
		private Dictionary<string, string> connectorToConnectionMap;
		public Dictionary<string, string> ConnectorToConnectionMap
		{
			get { return connectorToConnectionMap; }	
		}

		public ChildModule(XmlElement description)
			: this()
		{
			// read it!
			read(description);
		}

		private ChildModule()
		{
			this.connectorToConnectionMap = new Dictionary<string, string>();
		}

		public ChildModule Clone()
		{
			ChildModule clone = new ChildModule();

			clone.moduleImplementationName = this.moduleImplementationName;
			clone.moduleAlias = this.moduleAlias;

			foreach (string key in connectorToConnectionMap.Keys)
				clone.connectorToConnectionMap.Add(key, connectorToConnectionMap[key]);

			return clone;
		}

		private void read(XmlElement description)
		{
			System.Diagnostics.Trace.Assert(description is XmlElement);
			System.Diagnostics.Trace.Assert(description.Name == "Use");
			System.Diagnostics.Trace.Assert(description.HasAttribute("name"));

			// get name of child datapath
			moduleImplementationName = description.Attributes["entity"].Value;

			// name of this instance
			moduleAlias = description.Attributes["name"].Value;

			// get connectors and name of whatever is connected
			foreach (XmlElement element in description.GetElementsByTagName("Connect"))
			{
				System.Diagnostics.Trace.Assert(element.HasAttribute("connector"));
				System.Diagnostics.Trace.Assert(element.HasAttribute("channel"));

				string connector = element.Attributes["connector"].Value;
				string channel = element.Attributes["channel"].Value;

				connectorToConnectionMap.Add(connector, channel);
			}
		}
	}
}
